/**
 * 文件上传辅助工具
 */

import { uploadImage, uploadImages, getFileUrl } from '@/api/file'

/**
 * 验证图片文件
 * @param {File} file - 文件对象
 * @param {Object} options - 配置选项
 * @returns {Boolean} 是否通过验证
 */
export function validateImage(file, options = {}) {
  const {
    maxSize = 5, // MB
    allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
  } = options

  // 验证文件类型
  if (!allowedTypes.includes(file.type)) {
    return {
      valid: false,
      message: `只允许上传 ${allowedTypes.join(', ')} 格式的图片`
    }
  }

  // 验证文件大小
  const fileSizeMB = file.size / 1024 / 1024
  if (fileSizeMB > maxSize) {
    return {
      valid: false,
      message: `图片大小不能超过 ${maxSize}MB`
    }
  }

  return { valid: true }
}

/**
 * 压缩图片（可选功能）
 * @param {File} file - 图片文件
 * @param {Number} quality - 压缩质量 0-1
 * @returns {Promise<File>} 压缩后的文件
 */
export function compressImage(file, quality = 0.8) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      const img = new Image()
      img.src = e.target.result
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        
        canvas.width = img.width
        canvas.height = img.height
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        
        canvas.toBlob(
          (blob) => {
            const compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            resolve(compressedFile)
          },
          file.type,
          quality
        )
      }
      img.onerror = reject
    }
    reader.onerror = reject
  })
}

/**
 * 批量处理图片URL
 * @param {Array} fileList - 文件路径数组
 * @returns {Array} 完整URL数组
 */
export function batchGetFileUrls(fileList) {
  if (!Array.isArray(fileList)) return []
  return fileList.map(file => getFileUrl(file))
}

/**
 * 文件上传配置预设
 */
export const uploadPresets = {
  // 商品图片
  goods: {
    prefix: 'goods',
    maxSize: 5,
    accept: 'image/jpeg,image/jpg,image/png,image/gif',
    limit: 5
  },
  // 用户头像
  avatar: {
    prefix: 'user',
    maxSize: 2,
    accept: 'image/jpeg,image/jpg,image/png',
    limit: 1
  },
  // 轮播图
  banner: {
    prefix: 'banner',
    maxSize: 10,
    accept: 'image/jpeg,image/jpg,image/png',
    limit: 1
  },
  // 公告图片
  announcement: {
    prefix: 'announcement',
    maxSize: 5,
    accept: 'image/jpeg,image/jpg,image/png,image/gif',
    limit: 3
  }
}

export {
  uploadImage,
  uploadImages,
  getFileUrl
}
